package com.gz.servlet;

import com.google.gson.Gson;
import com.gz.entity.User;
import com.gz.service.UserService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

//jquery+ajax方法
@WebServlet(urlPatterns = "/checkUserServlet2")
public class CheckUserServlet2 extends HttpServlet {
    private UserService userService=new UserService();
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //记住这里的text/html要改成text/json
        response.setContentType("text/json;charset=utf-8");
        String username = request.getParameter("username");
        //到DB查询
        User userByName = userService.getUserByName(username);
        if (userByName != null) {//说明用户存在，返回用户的json格式字符串
            String strUser = new Gson().toJson(userByName);
            response.getWriter().write(strUser);
        }else {
            //!!!注意
            //这里不能和之前一样返回""，因为之前那个是"text/html;charset=utf-8"
            // 如response.getWriter().write("")
            //而这里是"text/json;charset=utf-8"，因为$.ajax({})中的dataType是json
            //必须返回User对的json类型
            //否则进入不了login2.html的success
            User user = new User(-1, "", "", "");
            String jsonnull = new Gson().toJson(user);
            response.getWriter().write(jsonnull);
        }
    }
}
